package org.liaohailong.victorlibrary

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.widget.Toast
import org.liaohailong.victorlibrary.ui.MainActivity

/**
 * Author: liaohailong
 * Date: 2019/3/23
 * Time: 10:02
 * Description: 监听本包安装完毕，自动启动
 **/
class PackageReplacedReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        intent?.apply {
            data?.apply {
                context?.apply {
                    val packageName = schemeSpecificPart
                    val defaultPackage = getPackageName()
                    val samePackageName = TextUtils.equals(packageName, defaultPackage)
                    if (!samePackageName) {
                        Toast.makeText(this, "未命中 $defaultPackage != $packageName", Toast.LENGTH_LONG).show()
                    }
                    val sameAction = TextUtils.equals(action, Intent.ACTION_PACKAGE_REPLACED)
                    if (samePackageName && sameAction) {
                        val mainIntent = Intent(this, MainActivity::class.java)
                        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        startActivity(mainIntent)
                    }
                }
            }
        }
    }
}